<template>
    <el-card class="box-card">
        <div class="searchInput">
            <el-input v-model="input" clearable placeholder="请输入搜索内容" @clear="queryByList()" style="width:240px;">
            </el-input>
            <el-button @click="handleSearch" style="margin-left: 10px;">搜索</el-button>
            <el-button @click="HandleAddEvent" style="margin-left: 10px;">添加
            </el-button>
        </div>

        <el-table :data="tableData" style="width: 100%" :default-sort="{ prop: 'userId', order: 'ascending' }">
            <el-table-column prop="userId" label="编号" sortable>
            </el-table-column>
            <el-table-column prop="userName" label="用户名">
            </el-table-column>
            <el-table-column prop="roleName" label="身份">
            </el-table-column>
            <el-table-column prop="email" label="邮箱">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
            </el-table-column>
            <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                    <el-tag type="" effect="dark">
                        <el-button @click="handleEdit(scope.row)" type="text" size="small" style="color:white">编辑
                        </el-button>
                    </el-tag>
                    <el-tag type="danger" effect="dark">
                        <el-button @click="handleDelete(scope.row)" type="text" size="small" style="color:white">删除
                        </el-button>
                    </el-tag>
                </template>
            </el-table-column>
        </el-table>


        <!--编辑用户信息对话框-->
        <el-dialog title="编辑信息" :visible.sync="dialogEditFormVisible" width="30%">
            <el-form :model="editForm">
                <el-form-item label="用户名" :label-width="formLabelWidth">
                    <el-input v-model="editForm.userName"></el-input>
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth">
                    <el-input v-model="editForm.password"></el-input>
                </el-form-item>
                <el-form-item label="身份" :label-width="formLabelWidth">
                    <el-select v-model="value" placeholder="请选择">
                        <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName"
                            :value="item.roleId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="editCancelHandle">取 消</el-button>
                <el-button type="primary" @click="editEnsureHandle">确 定</el-button>
            </div>
        </el-dialog>
        <!--添加用户对话框-->
        <el-dialog title="添加用户" :visible.sync="dialogFormVisible" width="28%">
            <el-form :model="form">
                <el-form-item label="用户名" :label-width="formLabelWidth">
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth">
                    <el-input v-model="form.password"></el-input>
                </el-form-item>
                <el-form-item label="身份" :label-width="formLabelWidth">
                    <el-select v-model="value" placeholder="请选择">
                        <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName"
                            :value="item.roleId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="addCancelHandle">取 消</el-button>
                <el-button type="primary" @click="addEnsureHandle">确 定</el-button>
            </div>
        </el-dialog>
        <div class="block">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page.sync="currentPage" :page-size="pageSize" :total="pageCount"
                layout="total, prev, pager, next, jumper" prev-text="上一页" next-text="下一页">
            </el-pagination>
        </div>
    </el-card>
</template>

<script>
export default {
    data() {
        return {
            tableData: [],
            input: '',
            form: {
                userName: '',
                password: '',
                email: '',
            },
            editForm: {
                userName: '',
                password: '',
                email: '',
            },
            roleList: [],
            user: {
                userId: '',
                userName: '',
                password: '',
                email: '',
                roleId: '',
                roleName: ''
            },
            value: '',
            currentPage: 1,
            pageSize: 5,
            pageCount: 1,
            label: '',
            dialogFormVisible: false,
            dialogEditFormVisible: false,
            formLabelWidth: '120px'
        }
    },
    created() {
        this.query();
        this.queryByList();
        this.queryRoleList();
    },
    methods: {
        query() {
            fetch('http://localhost/user/lists')
                .then(response => response.json())
                .then((data) => {
                    this.pageCount = data.data.length;
                    console.log(this.pageCount);
                })
        },
        queryByList() {
            fetch('http://localhost/user/list?pageNum=' + this.currentPage + '&pageSize=' + this.pageSize)
                .then(response => response.json())
                .then((data) => {
                    this.tableData = data.data;
                })
        },
        queryRoleList() {
            fetch('http://localhost/roles')
                .then(response => response.json())
                .then((data) => {
                    this.roleList = data.data;
                })
        },
        queryByPage(input, currentPage, pageSize) {
            fetch('http://localhost/user/query?str=' + input + '&pageNum=' + currentPage + '&pageSize=' + pageSize)
                .then(response => response.json())
                .then((data) => {
                    this.tableData = data.data;
                })
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
            if (this.input == null || this.input == '') {
                this.currentPage = val;
                this.queryByList();
            } else {
                this.queryByPage(this.input, val, this.pageSize);
            }
            // console.log(`当前页: ${val}`);
        },
        handleEdit(row) {
            this.user.userId = row.userId;
            this.user.userName = row.userName;
            this.user.password = row.password;
            this.user.email = row.email;
            this.user.roleId = row.roleId;
            this.dialogEditFormVisible = !this.dialogEditFormVisible;
            this.editForm.userName = row.userName;
            this.editForm.email = row.email;
            console.log(row);
        },
        handleDelete(row) {
            fetch('http://localhost/user/' + row.userId, {
                method: 'DELETE',
            })
                .then(result => {
                    if (result) {
                        for (let i = 0; i < this.tableData.length; i++) {
                            if (this.tableData[i].userId == row.userId) {
                                this.tableData.splice(i, 1);
                                break;
                            }
                        }
                    } else {
                        alert("删除失败");
                    }
                })
        },
        handleSearch() {
            // alert(this.input);
            fetch('http://localhost/user/queryByPage?str=' + this.input)
                .then(response => response.json())
                .then((data) => {
                    this.pageCount = data.data.length;
                })
            this.currentPage = 1;
            if (this.input) {
                this.queryByPage(this.input, this.currentPage, this.pageSize);
            }
        },
        HandleAddEvent() {
            this.dialogFormVisible = !this.dialogFormVisible;
        },
        isEmpty(obj) { //判断是否为空
            if (typeof obj == "undefined" || obj == null || obj == "") {
                return true;
            } else {
                return false;
            }
        },
        //编辑用户信息 对话框
        editCancelHandle() {
            this.dialogEditFormVisible = false;
        },
        editEnsureHandle() {
            fetch('http://localhost/role?id=' + this.value)
                .then(response => response.json())
                .then((data) => {
                    this.user.roleName = data.data.roleName;
                })
            //axios put请求更新用户角色 即user_role中的roleId    
            this.axios.put('http://localhost/user/update', {
                userId: this.user.userId,
                userName: this.isEmpty(this.editForm.userName) ? this.user.userName : this.editForm.userName,
                password: this.isEmpty(this.editForm.password) ? this.user.password : this.editForm.password,
                email: this.isEmpty(this.editForm.email) ? this.user.email : this.editForm.email,
                roleId: this.isEmpty(this.value) ? this.user.roleId : this.value
            })
                .then(result => {
                    if (result.data) {
                        for (let i = 0; i < this.tableData.length; i++) {
                            if (this.tableData[i].userId == this.user.userId) {
                                this.tableData[i].userName = this.editForm.userName;
                                this.tableData[i].password = this.editForm.password;
                                this.tableData[i].email = this.editForm.email;
                                this.tableData[i].roleId = this.value;
                                this.tableData[i].roleName = this.user.roleName;
                            }
                        }
                        console.log(result.data);
                    }
                })
            this.editForm.password = '';
            this.dialogEditFormVisible = false;
        },
        //添加用户 对话框
        addCancelHandle() {
            this.dialogFormVisible = false;
        },
        addEnsureHandle() {
            fetch('http://localhost/user/insert', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    userName: this.form.userName,
                    password: this.form.password,
                    email: this.form.email,
                    roleId: this.value
                })
            })
                .then((result) => {
                    this.query();
                    this.form.userName = '';
                    this.form.password = '';
                    this.form.email = '';
                    this.form.roleId = '';
                    console.log(result);
                })

            this.dialogFormVisible = false;
        }
    },
}
</script>

<style>
.text {
    font-size: 14px;
}

.item {
    padding: 18px 0;
}

.box-card {
    width: 480px;
}

.el-card {
    width: 90%;
    height: 90%;
    overflow: hidden;
    margin: 0 auto;
}

.searchInput {
    width: 420px;
    display: flex;
    left: 0;
}

.el-table .warning-row {
    background: oldlace;
}

.el-table .success-row {
    background: #f0f9eb;
}

.block {
    position: absolute;
    bottom: 50px;
}
</style>

